package com.chf.job.controller;

import com.chf.job.common.Const;
import com.chf.job.common.ServerResponse;
import com.chf.job.pojo.OpenService;
import com.chf.job.pojo.User;
import com.chf.job.service.IOpenService;
import com.chf.job.utils.CookieUtil;
import com.chf.job.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
public class OpenRecruitController {
    @Autowired
    private IOpenService iOpenService;

    /**
     * 开通招聘服务
     */
    @RequestMapping(value = "service/addService.html", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse addService(OpenService openService, HttpServletRequest request) {
        // 查询当前用户校验邮箱
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (!user.getEmail().equals(openService.getVerifyEmail())) {
            return ServerResponse.createByErrorMessage("认证失败");
        }
        int result = iOpenService.addService(openService);
        if (result > 0) {
            return ServerResponse.createBySuccess("添加成功", Const.OPEN_SERVICE_SECOND);
        }
        return ServerResponse.createByErrorMessage("认证失败");
    }

    /**
     * 更新招聘服务
     */
    @RequestMapping(value = "/service/updateService.html", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse updateService(OpenService openService, HttpServletRequest request) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        int result = iOpenService.updateService(openService, user.getEmail());
        if (result > 0) {
            return ServerResponse.createBySuccess("更新成功", Const.OPEN_SERVICE_SECOND);
        }
        return ServerResponse.createByErrorMessage("失败");
    }

    /**
     * 激活邮件真正开通招聘服务
     */
    @RequestMapping(value = "service/activeEmail.html")

    public String activeEmail(HttpServletRequest request, @RequestParam("email") String email, @RequestParam("emailToken") String emailToken) {
        // 去校验cookie中是否存在value
        String valueByCookie = CookieUtil.getValueByCookie(Const.ACTIVE_EMAIL_KEY, request);
        if (!MD5Util.MD5EncodeUtf8(emailToken).equals(valueByCookie)){
            return null;
        }
        // 更新开通服务数据库 中的字段状态
        int result = iOpenService.updateServiceStatus(email);
        if (result >0) {
            return "redirect:/page/addCompanyFirst.html";
        }
        return null;

    }
}

